class Solution {
    public int trap(int[] height) {
        Deque<Integer> st = new ArrayDeque<Integer>();
        int res = 0;
        for(int i =0;i<height.length;i++){
        while(!st.isEmpty()&&height[i]>=height[st.peek()])
        {
            int bott = height[st.pop()];
            if(st.isEmpty()) break;
            int left = height[st.peek()];
            int h = Math.min(left,height[i])-bott;
            res+=h*(i-st.peek()-1);
        }
        st.push(i);
        }
    return res;
    }
}